package com.beone.admin.controller;

import com.base.common.RequestContextUtils;
import com.base.common.util.algorithm.DigestUtils;
import com.beone.admin.entity.BaseUser;
import com.beone.admin.entity.SysLog;
import com.beone.admin.service.SysLogService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @title  后台首页控制器
 * @Author 覃球球
 * @Version 1.0 on 2018/1/25.
 * @Copyright 长笛龙吟
 */
@Controller
public class HomeController {

    @Autowired
    private UserCache userCache;

    @Autowired
    private SysLogService sysLogService;

    /**
     * index url
     * @param request
     * @return
     */
    @RequestMapping("/system/index")
    public String index(HttpServletRequest request){
        ControllerUtils.getAdminUser(request); //设置登录会话信息
        return "index";
    }


    /**
     * login url
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public String showLoginPage(HttpServletRequest request){
        String rememberMeCookie = RequestContextUtils.getCookieByName(
                TokenBasedRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, request);
        request.setAttribute("rememberMe", StringUtils.isNotBlank(rememberMeCookie));
        return "login";
    }


    /**
     * 用户登出操作
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception{
        BaseUser user = ControllerUtils.getAdminUser(request);
        if (user != null){
            userCache.removeUserFromCache(user.getUserAccount());
            SysLog log = new SysLog();
            log.setCreateTime(new Date());
            log.setType("LOGOUT");
            log.setContent("成功退出!");
            log.setIp(RequestContextUtils.getClientIp(request));
            log.setUsername(user.getUserAccount());
            sysLogService.insert(log);

            SecurityContextHolder.clearContext();
            request.getSession(false).invalidate();
        }
        /**
         * 清除缓存中的登录数据
         */
        return "redirect:/login?logout";
    }
}